<template>
  <!-- 热门课程列表组件 -->
  <div class="section hot-courses">
    <div class="container">
      <div class="section-header">
        <div class="section-title">
          <span class="title-icon"></span>
          <h2>热门课程</h2>
        </div>
      </div>
      <div class="section-tabs-container">
        <div class="section-tabs">
          <div 
            v-for="category in categories" 
            :key="category.id"
            class="tab" 
            :class="{ active: selectedCategory === category.id }"
            @click="filterByCategory(category.id)"
          >{{ category.name }}</div>
        </div>
        <!-- 更多课程链接 -->
        <div class="more-link" @click="seeMoreCourses">更多课程 <el-icon><ArrowRight /></el-icon></div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="fetchCourses" class="retry-button">重试</button>
    </div>
    
    <!-- 课程列表 -->
    <div v-else class="course-list">
      <div 
        v-for="course in displayedCourses" 
        :key="course.courseId" 
        class="course-card"
        @click="goToCourseDetail(course.courseId)"
      >
        <!-- 课程封面图 -->
        <div class="course-image" :style="{ backgroundImage: 'url(' + getImageUrl(course) + ')' }">
          <div class="course-tag" v-if="course.recommendWeight >= 10">热门</div>
        </div>
        <!-- 课程信息 -->
        <div class="course-info">
          <h3 class="course-title">{{ course.title }}</h3>
          <div class="course-meta">
            <span class="course-school">分类: {{ getCategoryName(course.categoryId) }}</span>
          </div>
          <div class="course-stats">
            <div class="stat">
              <i class="el-icon-user"></i>
              <span>学习人数: {{ course.studyPeople || '暂无数据' }}</span>
            </div>
          </div>
          <div class="course-price" :class="{'free': course.price === 0}">
            {{ course.price === 0 ? '免费' : '¥' + course.price.toFixed(2) }}
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="!loading && !error && displayedCourses.length === 0" class="empty-container">
      <p>暂无课程信息</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { getHotCourses } from '@/api/course'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { ArrowRight } from '@element-plus/icons-vue'

/**
 * 热门课程列表组件
 * 展示热门课程，支持分类筛选和课程详情跳转
 */
export default {
  name: 'HotCourseList',
  
  components: {
    ArrowRight
  },
  
  setup() {
    // 状态管理
    const courses = ref([])                // 课程列表数据
    const loading = ref(true)              // 加载状态
    const error = ref('')                  // 错误信息
    const selectedCategory = ref(0)        // 选中的分类ID
    const allCourses = ref([])             // 所有课程数据
    const router = useRouter()             // 路由实例
    
    /**
     * 课程分类定义
     * @type {Array<{id: number, name: string}>}
     */
    const categories = [
      { id: 0, name: '全部' },
      { id: 1, name: '学术' },
      { id: 2, name: '技术与工程' },
      { id: 3, name: '商业与管理' },
      { id: 4, name: '艺术与设计' },
      { id: 5, name: '职业技能' },
      { id: 6, name: '健康与医学' },
      { id: 7, name: '语言与文化' },
      { id: 8, name: '科技与未来趋势' },
      { id: 9, name: '体育与健身' }
    ]
    
    /**
     * 获取分类名称
     * @param {number} categoryId - 分类ID
     * @returns {string} 分类名称
     */
    const getCategoryName = (categoryId) => {
      const category = categories.find(c => c.id === categoryId)
      return category ? category.name : `分类${categoryId}`
    }
    
    /**
     * 根据选中分类筛选课程
     * @returns {Array} 筛选后的课程列表
     */
    const displayedCourses = computed(() => {
      if (selectedCategory.value === 0) {
        return courses.value;
      } else {
        return courses.value.filter(course => {
          const courseCategoryId = Number(course.categoryId);
          const selectedId = Number(selectedCategory.value);
          return courseCategoryId === selectedId;
        });
      }
    });
    
    /**
     * 根据分类ID筛选课程
     * @param {number} categoryId - 分类ID
     */
    const filterByCategory = (categoryId) => {
      selectedCategory.value = Number(categoryId);
    };
    
    /**
     * 获取课程数据
     */
    const fetchCourses = async () => {
      loading.value = true
      error.value = ''
      
      try {
        // 从API获取课程数据
        const response = await getHotCourses(1, 20) // 获取第一页最多20条数据
        
        if (response && response.code === 200 && response.data && response.data.records) {
          // 确保所有课程数据都有基本属性
          const validCourses = response.data.records.map(course => {
            // 确保推荐权重有值，默认为0
            if (course.recommendWeight === undefined || course.recommendWeight === null) {
              course.recommendWeight = 0;
            }
            // 确保学习人数有值，默认为0
            if (course.studyPeople === undefined || course.studyPeople === null) {
              course.studyPeople = 0;
            }
            return course;
          });
          
          // 按照推荐权重降序排序，确保优先展示权重高的课程
          const sortedCourses = validCourses.sort((a, b) => {
            return b.recommendWeight - a.recommendWeight;
          });
          
          // 取前8个课程显示
          const topCourses = sortedCourses.slice(0, 8);
          
          if (topCourses.length > 0) {
            // 先将所有课程保存起来
            allCourses.value = topCourses;
            courses.value = topCourses;
          } else {
            // 如果没有数据，使用备用数据
            const backupCourses = [
              {
                "courseId": 130001,
                "teacherId": 110001,
                "title": "现代文学赏析",
                "details": "https://example.com/course_cover1.jpg",
                "categoryId": 1,
                "price": 99.99,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 1200,
                "createTime": "2025-03-14T00:20:36.000+00:00"
              },
              {
                "courseId": 130002,
                "teacherId": 110002,
                "title": "高等数学基础",
                "details": "https://example.com/course_cover2.jpg",
                "categoryId": 2,
                "price": 199.99,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 1500,
                "createTime": "2025-03-14T00:20:36.000+00:00"
              },
              {
                "courseId": 130003,
                "teacherId": 110026,
                "title": "英语听说强化训练",
                "details": "面向初学者的英语听说入门教程。",
                "categoryId": 3,
                "price": 99.99,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 2000,
                "createTime": "2025-03-21T03:53:44.000+00:00"
              },
              {
                "courseId": 130004,
                "teacherId": 110026,
                "title": "大学物理实验",
                "details": "大学物理实验课程。",
                "categoryId": 4,
                "price": 149.99,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 800,
                "createTime": "2025-03-21T03:53:44.000+00:00"
              },
              {
                "courseId": 130006,
                "teacherId": 110026,
                "title": "有机化学基础",
                "details": "学习有机化学的基本原理和应用。",
                "categoryId": 5,
                "price": 129.99,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 750,
                "createTime": "2025-03-21T03:53:44.000+00:00"
              },
              {
                "courseId": 130007,
                "teacherId": 110026,
                "title": "世界地理概览",
                "details": "了解世界各地的地理、文化和经济特点。",
                "categoryId": 6,
                "price": 179.99,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 950,
                "createTime": "2025-03-21T03:53:44.000+00:00"
              },
              {
                "courseId": 130008,
                "teacherId": 110026,
                "title": "细胞生物学导论",
                "details": "学习细胞的基本结构和功能。",
                "categoryId": 7,
                "price": 159.99,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 650,
                "createTime": "2025-03-21T03:53:44.000+00:00"
              },
              {
                "courseId": 130009,
                "teacherId": 110026,
                "title": "书法艺术入门",
                "details": "学习中国传统书法艺术。",
                "categoryId": 8,
                "price": 0,
                "status": 1,
                "recommendWeight": 1,
                "studyPeople": 1800,
                "createTime": "2025-03-21T03:53:44.000+00:00"
              }
            ];
            allCourses.value = backupCourses;
            courses.value = backupCourses;
          }
        } else {
          error.value = '获取课程数据失败';
        }
      } catch (err) {
        error.value = '获取课程数据失败，请稍后重试';
      } finally {
        loading.value = false;
      }
    };
    
    /**
     * 获取课程图片URL
     * @param {Object} course - 课程对象
     * @returns {string} 图片URL
     */
    const getImageUrl = (course) => {
      // 优先使用titleImg字段
      if (course.titleImg) {
        return course.titleImg;
      } 
      // 检查是否有OSS图片资源
      else if (course.ossImages && Array.isArray(course.ossImages) && course.ossImages.length > 0) {
        // OSS图片可能是对象数组或字符串
        if (typeof course.ossImages[0] === 'object' && course.ossImages[0].url) {
          return course.ossImages[0].url;
        } else if (typeof course.ossImages[0] === 'string') {
          return course.ossImages[0];
        } else {
          return course.ossImages;
        }
      } 
      // 检查details是否为图片URL
      else if (course.details && typeof course.details === 'string' && course.details.startsWith('http')) {
        return course.details;
      }
      // 使用默认占位图
      else {
        const defaultImages = [
          'https://edu-image.nosdn.127.net/C7F81100F90F8DB85704C901C4CFFC9D.jpg',
          'https://edu-image.nosdn.127.net/7254a20d-daa7-40ab-8325-f91b0a31ec57.jpg',
          'https://edu-image.nosdn.127.net/9bc87ea8-b0e0-46d1-a773-90e2861575a5.jpg',
          'https://edu-image.nosdn.127.net/8e9f8a08-2fa3-4850-8d5c-b812c2d91d70.jpg',
          'https://edu-image.nosdn.127.net/ac00a34c87654a7d933eb9d113130dc8.png'
        ];
        
        // 使用课程ID来选择一个默认图片
        const index = (course.courseId || 0) % defaultImages.length;
        return defaultImages[index];
      }
    }
    
    /**
     * 跳转到更多课程页面
     */
    const seeMoreCourses = () => {
      router.push('/courses')
    }
    
    /**
     * 跳转到课程详情页面
     * @param {string|number} courseId - 课程ID
     */
    const goToCourseDetail = (courseId) => {
      // 确保courseId是字符串类型
      const courseIdStr = String(courseId)
      
      // 使用try-catch防止导航错误
      try {
        router.push({
          name: 'CourseDetail',
          params: { id: courseIdStr }
        }).then(() => {
          // 导航完成后延迟100ms刷新页面
          setTimeout(() => {
            window.location.reload()
          }, 0)
        })
      } catch (err) {
        ElMessage.error('跳转到课程详情页面失败')
      }
    }
    
    // 组件挂载时获取课程数据
    onMounted(() => {
      fetchCourses()
      // 默认选中"全部"分类
      selectedCategory.value = 0
    })
    
    return {
      courses,
      loading,
      error,
      fetchCourses,
      getImageUrl,
      seeMoreCourses,
      selectedCategory,
      filterByCategory,
      displayedCourses,
      getCategoryName,
      goToCourseDetail,
      categories
    }
  }
}
</script>

<style scoped>
.section {
  padding: 30px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.section-header {
  margin-bottom: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.title-icon {
  width: 4px;
  height: 24px;
  background-color: #1890ff;
  margin-right: 12px;
  border-radius: 2px;
}

.section-title h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
  letter-spacing: 1px;
}

.section-tabs-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.tab {
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
}

.tab:hover {
  background-color: #f5f7fa;
}

.tab.active {
  color: #1890ff;
  background-color: #e6f7ff;
  font-weight: 500;
}

/* 加载状态容器 */
.loading-container, .error-container, .empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem;
  text-align: center;
}

/* 加载动画 */
.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

/* 加载动画关键帧 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 重试按钮 */
.retry-button {
  margin-top: 1rem;
  background: #1890ff;
  color: white;
  border: none;
  padding: 0.5rem 1.5rem;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
}

/* 重试按钮悬停效果 */
.retry-button:hover {
  background: #096dd9;
}

/* 课程列表网格布局 */
.course-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

/* 课程卡片样式 */
.course-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

/* 课程卡片悬停效果 */
.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.08);
}

/* 课程封面图 */
.course-image {
  height: 160px;
  background-size: cover;
  background-position: center;
  position: relative;
}

/* 课程标签 */
.course-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 2px 8px;
  background-color: #ff6b6b;
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

/* 课程信息区域 */
.course-info {
  padding: 15px;
}

/* 课程标题 */
.course-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 课程元信息 */
.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

/* 课程统计信息 */
.course-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

/* 统计项 */
.stat {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

/* 统计图标 */
.stat i {
  margin-right: 5px;
  font-size: 14px;
}

/* 课程价格 */
.course-price {
  font-size: 16px;
  font-weight: 500;
  color: #ff6b6b;
}

/* 免费课程价格样式 */
.course-price.free {
  color: #52c41a;
}

/* 更多课程链接 */
.more-link {
  color: #1890ff;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
}

.more-link:hover {
  color: #096dd9;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .course-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .course-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .course-list {
    grid-template-columns: 1fr;
  }
}
</style> 